//
//  TSImageResultViewController.m
//  TSDemo_ImageFilter
//
//  Created by ciyouzen on 2021/3/10.
//

#import "TSImageResultViewController.h"
#import <Masonry/Masonry.h>
#import <CQDemoKit/CJUIKitAlertUtil.h>

@interface TSImageResultViewController () {
    
}
@property (nonatomic, strong, readonly) UIImage *resultImage;

@end

@implementation TSImageResultViewController

- (instancetype)initWithResultImage:(UIImage *)resultImage {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _resultImage = resultImage;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"保存到相册", nil) style:UIBarButtonItemStylePlain target:self action:@selector(saveImage)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(20);
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.mas_topLayoutGuide).mas_offset(20);
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuide).mas_offset(-20);
    }];
    imageView.image = self.resultImage;
}

#pragma mark - 保存至相册
- (void)saveImage {
    [self saveImageToPhotoAlbum:self.resultImage];
}


- (void)saveImageToPhotoAlbum:(UIImage *)savedImage {
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

//指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (image == nil) {
        return;
    }
    NSString *msg = @"保存图片成功";
    if(error != NULL){
        msg = @"保存图片失败" ;
    }
    [CJUIKitAlertUtil showIKnowAlertInViewController:self withTitle:msg iKnowBlock:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
